package com.cy.dda.service.user.impl;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cy.dda.comm.utils.CommonUtils;
import com.cy.dda.dao.mapper.user.UserMapper;
import com.cy.dda.dao.mapper.user.UserWechatMapper;
import com.cy.dda.model.domain.user.User;
import com.cy.dda.model.domain.user.UserWechat;
import com.cy.dda.service.BaseService;
import com.cy.dda.service.user.UserWechatService;

/**
 * 用户-微信关联服务 UserWechatService
 *
 * @author: tanyilin
 * @create: 2018年11月21日 下午5:30:41
 */
@Service
public class UserWechatServiceImpl extends BaseService implements UserWechatService {

	@Autowired
	private UserMapper userMapper;
	@Autowired
	private UserWechatMapper userWechatMapper;
	
	@Override
	public UserWechat queryByUserIdInCache(Long userId) {
		UserWechat userWechat = new UserWechat();
		userWechat.setUserId(userId);
		userWechat = userWechatMapper.selectOne(userWechat);
		return userWechat;
	}
	
	@Override
	public UserWechat queryByOpenIdInCache(String openId) {
		UserWechat userWechat = new UserWechat();
		userWechat.setOpenId(openId);
		userWechat = userWechatMapper.selectOne(userWechat);
		return userWechat;
	}
	
	@Override
	@Transactional
	public void inserUserWechat(UserWechat userWechat) {
		//先删除
		//删除openId旧绑定关系
		UserWechat delOpenId = new UserWechat();
		delOpenId.setOpenId(userWechat.getOpenId());
		userWechatMapper.delete(delOpenId);
		
		//删除userId旧绑定关系
        UserWechat delUserId = new UserWechat();
        delUserId.setUserId(userWechat.getUserId());
        userWechatMapper.delete(delUserId);
        
        //再新增
        Date time = new Date();
        userWechat.setCreateTime(time);
        userWechat.setUpdateTime(time);
        userWechatMapper.insertSelective(userWechat);
        
        //更新user里的头像地址
		if(!CommonUtils.isEmpty(userWechat.getHeadImg())) {
			
			User updateUser = new User();
			updateUser.setId(userWechat.getUserId());
			updateUser.setHeadImg(userWechat.getHeadImg());
			updateUser.setUpdateTime(time);
			userMapper.updateByPrimaryKeySelective(updateUser);
		}
		
	}
	
	@Override
	@Transactional
	public void updateUserWechat(UserWechat userWechat) {

		//更新用户-微信关联关系UserWechat
		Date time = new Date();
		userWechat.setUpdateTime(time);
		userWechatMapper.updateByPrimaryKeySelective(userWechat);
		
		//更新user里的头像地址
		if(!CommonUtils.isEmpty(userWechat.getHeadImg())) {
			
			User updateUser = new User();
			updateUser.setId(userWechat.getUserId());
			updateUser.setHeadImg(userWechat.getHeadImg());
			updateUser.setUpdateTime(time);
			userMapper.updateByPrimaryKeySelective(updateUser);
		}
		
	}
	
	@Override
	@Transactional
	public void deleteUserWechat(UserWechat userWechat) {

		userWechatMapper.delete(userWechat);
	}
	
	
	
}
